package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        1、判断当前的请求是否为登录请求，如果是直接放行
//            获取请求url
        String path = request.getURI().getPath(); // login/in
        if(path.contains("/login")){
//            直接放行
            return chain.filter(exchange);
        }
//        2、判断token
//   2.1 先判断请求头中是否有token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();  //直接返回给浏览器
        }
//        2.2 判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int status = AppJwtUtil.verifyToken(claimsBody);
//        -1：有效，0：有效
        if(status==-1||status==0){
//            解析成功，把userId和name放到请求头中继续进入到微服务中
           Integer userId =  claimsBody.get("userId",Integer.class);
           String name =   claimsBody.get("name",String.class);
           request.mutate().header("userId",userId.toString());
           request.mutate().header("name",name);
//           继续进入到后面的微服务中
           return chain.filter(exchange);

        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
